import Router from 'koa-router';
import response from '../../response.js';
import { readFile } from 'node:fs/promises';
import { createReadStream } from 'node:fs';

import config from '../../config.js';
import path from 'node:path';

const router = new Router();
router.post('/', async (ctx) => {
  if (!ctx?.file) {
    ctx.body = response.fail({
      msg: 'fail',
      errno: 1,
      message: 'fail',
    });
  } else {
    ctx.body = response.success({
      msg: 'success',
      errno: 0,
      data: {
        url: ctx?.file?.url,
        alt: ctx?.file?.url,
        href: ctx?.file?.url,
      },
    });
  }
});
router.get('/:fileName', async (ctx) => {
  const { fileName } = ctx.params || {};
  if (!fileName) {
    ctx.body = response.fail({ msg: 'fail' });
    return;
  }
  
  ctx.set('Content-Type', 'image/jpeg');
  ctx.set('access-control-allow-origin', '*');
  ctx.body = createReadStream(path.join(config.uploadPath, fileName));
});
export default router;
